package cn.bitkit.tools.crypto;


import cn.bitkit.base.util.StringUtil;

import javax.crypto.spec.SecretKeySpec;

public class SecretKey {

    /**
     * 定长秘钥,不足补0
     * @param strKey
     * @return
     */
    public static SecretKeySpec paddingKey(String strKey, String algorithm) {
        byte[] keyBytes = strKey.getBytes();
        return paddingByteKey(keyBytes, algorithm);
    }

    public static SecretKeySpec paddingHexKey(String hexKey, String algorithm) {
        byte[] keyBytes = StringUtil.hexStrToBytes(hexKey);
        return paddingByteKey(keyBytes, algorithm);
    }

    public static SecretKeySpec paddingByteKey(byte[] keyBytes, String algorithm) {
        /** keySize必须为64的倍数(单位bit), 也就是说keyBytes必须为8的倍数 */
        if(keyBytes.length % 8 != 0){
            /** 补全为8的倍数 */
            int length = (keyBytes.length/8+1)*8;
            /** 最小为128bit, 16byte */
            length = Math.max(length, 16);
            byte[] keys = new byte[length];
            for (int i = 0; i < keyBytes.length && i < keys.length; i++) {
                keys[i] = keyBytes[i];
            }
            keyBytes = keys;
        }
        return new SecretKeySpec(keyBytes, algorithm);
    }
}
